<?php
header('Content-Type: application/json');

class Api
{
    private $db = 'data.json'; // 这里应该配置实际的数据库连接,示例中使用简单的JSON文件存储

    public function handleRequest()
    {
        $action = $_REQUEST['action'] ?? '';
        if (method_exists($this, $action)) {
            $this->$action();
        } else {
            $this->sendErrorResponse('无效的操作');
        }
    }

    private function getUsers()
    {
        $page = (int)($_GET['page'] ?? 1);
        $perPage = 10;

        $users = $this->loadUsers();
        $start = ($page - 1) * $perPage;
        $this->sendResponse(array_slice($users, $start, $perPage));
    }

    private function addUser()
    {
        $username = $_POST['username'] ?? '';
        $email = $_POST['email'] ?? '';

        if (empty($username) || empty($email)) {
            $this->sendErrorResponse('用户名和邮箱不能为空');
            return;
        }

        $users = $this->loadUsers();
        $users[] = ['username' => $username, 'email' => $email];

        file_put_contents($this->db, json_encode($users));
        $this->sendResponse('添加用户成功(*^_^*)');
    }

    private function upload()
    {
        $file = $_FILES['file'] ?? null;
        if (!$file) {
            $this->sendErrorResponse('没有待上传文件');
            return;
        }

        $allowedTypes = []; // ['image/jpeg', 'image/png', 'image/gif'];
        $maxSize = 100 * 1024 * 1024; // 100MB

        if (!empty($allowedTypes) && !in_array($file['type'], $allowedTypes)) {
            $this->sendErrorResponse('不支持的文件类型');
            return;
        }

        if ($file['size'] > $maxSize) {
            $this->sendErrorResponse('文件大小超过限制');
            return;
        }

        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) {
            if (!mkdir($uploadDir, 0777, true)) {
                $this->sendErrorResponse('创建上传目录失败');
                return;
            }
        }

        $filename = uniqid() . '_' . $file['name'];
        if (move_uploaded_file($file['tmp_name'], $uploadDir . $filename)) {
            $this->sendResponse(['filename' => $filename]);
        } else {
            $this->sendErrorResponse('文件上传失败');
        }
    }

    private function loadUsers()
    {
        return file_exists($this->db) ? json_decode(file_get_contents($this->db), true) : [];
    }

    private function sendResponse($data, $success = true)
    {
        echo json_encode(['success' => $success, 'data' => $data]);
        exit;
    }

    private function sendErrorResponse($message)
    {
        $this->sendResponse(['message' => $message], false);
    }
}

(new Api())->handleRequest();
